
import 'package:flutter/material.dart';
import 'package:rc_widget/rc_widget.dart';
import 'package:flutter_study/widgets/public/themes/index.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';

import 'package:flutter_study/controllers/base/app_getx_controller.dart'
    show LoadingStatus;

export 'package:flutter_study/controllers/base/app_getx_controller.dart'
    show LoadingStatus;

class AppLoadingView extends StatelessWidget {
  const AppLoadingView({
    super.key,
    this.child,
    this.reload,
    this.margin,
    this.builder,
    this.status = LoadingStatus.loading,
  });

  final Widget? child;
  final LoadingStatus status;
  final void Function()? reload;
  final Widget Function()? builder;
  final EdgeInsetsGeometry? margin;

  @override
  Widget build(BuildContext context) {
    switch (status) {
      case LoadingStatus.loading:
        return _buildLoad();
      case LoadingStatus.error:
        return _buildError();
      default:
        return _buildSuccess();
    }
  }

  Widget _buildLoad() {
    return LayoutBuilder(builder: (_, size) {
      return Container(
          alignment: Alignment.topCenter,
          margin: margin ?? EdgeInsets.only(top: size.maxHeight * 0.4),
          child: UnconstrainedBox(
            child: SpinKitCircle(
              color: AppThemes.of().colors.spinkit,
              size: 60.sp,
            ),
          ));
    });
  }

  Widget _buildError() {
    return LayoutBuilder(builder: (_, size) {
      return Container(
          alignment: Alignment.center,
          margin: margin ?? EdgeInsets.only(top: size.maxHeight * 0.4),
          child: TextButton(
              onPressed: reload,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(
                    Icons.error,
                    size: 80.sp,
                    color: Colors.red,
                  ),
                  SizedBox(
                    height: 16.h,
                  ),
                  Text('加载失败，点击重试',
                      style: AppThemes.of()
                          .w400Text128
                          .copyWith(color: Colors.red))
                ],
              )));
    });
  }

  Widget _buildSuccess() {
    if (builder != null) {
      return builder!();
    } else {
      return child ?? const SizedBox();
    }
  }
}
